package com.huaxin.common.message.mp3recorder.audio;

import android.util.Log;

public class AudioCodec {

    /* quality
         * 1 : 4kbps (very noticeable artifacts, usually intelligible)
         * 2 : 6kbps (very noticeable artifacts, good intelligibility)
         * 4 : 8kbps (noticeable artifacts sometimes)
         * 6 : 11kpbs (artifacts usually only noticeable with headphones)
         * 8 : 15kbps (artifacts not usually noticeable)
         */
    private static final int DEFAULT_COMPRESSION = 6;

    static void load() {
        System.loadLibrary("speex");
//        System.loadLibrary("audiowrapper");
    }

    static boolean init = false;

    public static void initCodec(int mode) {
        if (!init) {
            init = true;
            recv = false;
            load();
            //audio_codec_init(mode);
            open(DEFAULT_COMPRESSION);
            Log.e("AudioCodec", " speex库加载完毕:" + getFrameSize());
            AudioConfig.BUFFER_FRAME_SIZE = getFrameSize();
        }
    }

    public static void closeCodec() {
        if (init) {
            init = false;
            recv = false;
            close();
        }
    }

    // initialize decoder and encoder
    //public static native int audio_codec_init(int mode);

    // encode
    //public static native int audio_encode(byte[] sample, int sampleOffset, int sampleLength, byte[] data, int dataOffset);

    // decode
    //public static native int audio_decode(byte[] data, int dataOffset, int dataLength, byte[] sample, int sampleLength);

    private static native int open(int compression);

    public static native int encode(short lin[], int offset, byte encoded[], int size);

    public static native int decode(byte encoded[], short lin[], int size);

    private static native void close();

    public static native int getFrameSize();

    /*echo cancellation*/
    private static native int echoplayback(short[] play);

    private static native int echocapture(short[] rec, short[] out);

    //在收到语音后开始处理
    static boolean recv = false;

    public static void playback(short[] play) {
        recv = true;
        echoplayback(play);
    }

    public static void capture(short[] rec, short[] out) {
        echocapture(rec, out);
    }

    public static boolean hadRecv() {
        return recv;
    }
}
